<?php

namespace api\modules\mini\controllers;

use api\controllers\OnAuthController;
use api\modules\mini\forms\LoginForm;
use common\factory\EasyWeChat;
use common\models\api\AccessToken;
use common\helpers\CommonHelper;
use services\api\AccessTokenService;
use services\spoker\SpokerService;
use services\system\SystemConfigService;
use services\user\UserService;
use Yii;

/**
 * 登录接口
 *
 * Class SiteController
 * @package api\modules\v1\controllers
 */
class SiteController extends OnAuthController
{
    public $modelClass = '';

    /**
     * 不用进行登录验证的方法
     *
     * 例如： ['index', 'update', 'create', 'view', 'delete']
     * 默认全部需要验证
     *
     * @var array
     */
    protected $authOptional = ['wx-login', 'index'];

    /**
     * @api {get} /mini/site/index 小程序首页
     * @apiName index
     * @apiGroup MiniSite
     *
     *
     * @apiSuccess {Object}  data                       返回数据
     * @apiSuccess {String}  data.title                 标题
     * @apiSuccess {String}  data.type                  类型【1图片、2视频】
     * @apiSuccess {Array}   data.image                 图片
     * @apiSuccess {String}  data.video                 视频
     * @apiSuccess {String}  data.content               内容
     */
    public function actionIndex()
    {
        // 记录登录信息
        $service = new SystemConfigService();
        return $service->getMiniIndex();
    }

    /**
     * @api {get} /mini/site/spoker-info 获取代言人信息
     * @apiName spoker-info
     * @apiGroup MiniSite
     *
     *
     * @apiSuccess {Object}  data               返回数据
     * @apiSuccess {Number}  data.id            代言人ID
     * @apiSuccess {Number}  data.status        代言人状态【0待审核、1审核通过、2审核失败】
     * @apiSuccess {Number}  data.switch        是否有切换正式测试权限
     */
    public function actionSpokerInfo()
    {
        // 记录登录信息
        $service = new SpokerService();
        return $service->getUserInfo();
    }

    /**
     * @api {post} /mini/site/wx-login 小程序登陆
     * @apiName wx-login
     * @apiGroup MiniSite
     *
     * @apiBody  {String} code                          小程序code
     *
     * @apiSuccess {Object}  data                       返回数据
     * @apiSuccess {String}  data.access_token          token
     */
    public function actionWxLogin()
    {
//        var_dump(Yii::$app->security->generatePasswordHash(Member::DEFAULT_PASSWORD));
//        var_dump(Yii::$app->security->generateRandomString());
//        exit();
        $params = Yii::$app->request->post();

        // {"session_key":"BzbOwcEGlyABTnBzGe4k7g==","openid":"oG_uU6_-EkhBuvHIO40S-4_ECo6w"}
        $app = EasyWeChat::miniProgram();
        $data = $app->auth->session($params['code']);
        $params['openid'] = $data['openid'] ?? "";
        if (empty($params['openid'])) {
            return CommonHelper::api(422, $data['errmsg'] ?? 'error code');
        }
        $params['group'] = AccessToken::GROUP_WX_MINI;
        $model = new LoginForm();
        $model->attributes = $params;
        if (!$model->validate()) {
            return CommonHelper::api(422, $this->getError($model));
        }

        // 记录登录信息
        $service = new AccessTokenService();
        return $service->getMiniAccessToken($model);
    }

    /**
     * @api {post} /mini/site/get-wx-phone   获取微信手机号
     * @apiName get-wx-phone
     * @apiGroup MiniSite
     * @apiUse CommonParam
     *
     * @apiBody  {String} code                  小程序code
     *
     * @apiSuccess {Object}  data               返回数据
     * @apiSuccess {String}  data.mobile               手机号
     */
    public function actionGetWxPhone()
    {
        $params = Yii::$app->request->post();
//        {"errcode":0,"errmsg":"ok","phone_info":{"phoneNumber":"18056280357","purePhoneNumber":"18056280357","countryCode":"86","watermark":{"timestamp":1698301491,"appid":"wx4348d2877f6b08ca"}}}
        $app = EasyWeChat::miniProgram();
        $data = $app->phone_number->getUserPhoneNumber($params['code']);
        $mobile = $data['phone_info']['phoneNumber'] ?? '';
        // 更新手机号
        UserService::updateWxMobile($mobile);
        return [
            'mobile' => $mobile
        ];
    }

    /**
     * @api {post} /mini/site/logout 登出
     * @apiName logout
     * @apiGroup MiniSite
     * @apiUse CommonParam
     *
     * @apiSuccess {Object}  data           返回数据
     */
    public function actionLogout()
    {
        $service = new AccessTokenService();
        return $service->logout();
    }
}
